package net.k3rnel.abugadro;

import java.util.HashMap;

import net.k3rnel.abugadro.Project.Projects;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

/**
 * This class is depracated. Leaving only for backwards-compatibility reasons. 
 * @author Nushio
 *
 */
public class ProjectsContentProvider  extends ContentProvider {

	private static final String DATABASE_NAME = "abugadro.db";
	private static final int DATABASE_VERSION = 2;
	private static final String PROJECTS_TABLE_NAME = "projects";
	public static final String AUTHORITY = "net.k3rnel.abugadro.internal";

	private static final UriMatcher sUriMatcher;

	private static final int PROJECTS = 1;
	private static final int PROJECT = 2;

	private static HashMap<String, String> projectsProjectionMap;

	private static class DatabaseHelper extends SQLiteOpenHelper {
		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE " + PROJECTS_TABLE_NAME + " ("
					+ Projects._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
					+ Projects.NAME + " TEXT NOT NULL ,"
					+ Projects.TYPE + " INTEGER NOT NULL,"
					+ Projects.LASTSYNC + " TIMESTAMP DATE DEFAULT (datetime('now','localtime')) "
					+")");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			while(oldVersion < DATABASE_VERSION){
				oldVersion++;
				switch(oldVersion){
				case 2:
					db.execSQL("CREATE TABLE " + PROJECTS_TABLE_NAME + "_TEMP ("
							+ Projects._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
							+ Projects.NAME + " TEXT NOT NULL ,"
							+ Projects.TYPE + " INTEGER NOT NULL,"
							+ Projects.LASTSYNC + " TIMESTAMP DATE DEFAULT (datetime('now','localtime')) "
							+")");
					db.execSQL("INSERT INTO " + PROJECTS_TABLE_NAME + "_TEMP SELECT "
							+ Projects._ID + ", "
							+ Projects.NAME + ", "
							+ Projects.TYPE + ", "
							+ "updated FROM "+PROJECTS_TABLE_NAME
							+"");
					db.execSQL("DROP TABLE " + PROJECTS_TABLE_NAME);
					db.execSQL("ALTER TABLE " + PROJECTS_TABLE_NAME+"_TEMP RENAME TO "+PROJECTS_TABLE_NAME);
					db.setVersion(oldVersion);
					break;
				}
			}
		}
	}

	private DatabaseHelper dbHelper;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		int count;
		switch (sUriMatcher.match(uri)) {
		case PROJECTS:
			count = db.delete(PROJECTS_TABLE_NAME, selection, selectionArgs);
			break;
		case PROJECT:
			count = db.delete(PROJECTS_TABLE_NAME, Projects._ID + " = " + uri.getPathSegments().get(1), selectionArgs);			
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
		case PROJECTS:
			return Projects.CONTENT_TYPE_DIR;
		case PROJECT:
			return Projects.CONTENT_TYPE_ITEM;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		final SQLiteDatabase db = dbHelper.getWritableDatabase();
		final int match = sUriMatcher.match(uri);
		switch (match) {
		case PROJECTS:{
			db.insertOrThrow(PROJECTS_TABLE_NAME,"",values);
			return Projects.buildUri(values.getAsString(Projects._ID));
		}
		default: {
			throw new UnsupportedOperationException("Unknown uri: " + uri);
		}
		}
	}

	@Override
	public boolean onCreate() {
		dbHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		switch (sUriMatcher.match(uri)) {
		case PROJECTS:
			qb.setTables(PROJECTS_TABLE_NAME);
			qb.setProjectionMap(projectsProjectionMap);
			break;
		case PROJECT:
			qb.setTables(PROJECTS_TABLE_NAME);
			qb.setProjectionMap(projectsProjectionMap);
			qb.appendWhere(Projects._ID + " = " + uri.getPathSegments().get(1));   
			break;
		default:
			throw new IllegalArgumentException("Unknown URI on Query: " + uri);
		}

		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		int count;
		switch (sUriMatcher.match(uri)) {
		case PROJECTS:
			count = db.update(PROJECTS_TABLE_NAME, values, selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI on Update " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;

	}
	static {
		sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		sUriMatcher.addURI(AUTHORITY, PROJECTS_TABLE_NAME, PROJECTS);
		sUriMatcher.addURI(AUTHORITY, PROJECTS_TABLE_NAME+"/*", PROJECT);

		projectsProjectionMap = new HashMap<String, String>();
		projectsProjectionMap.put(Projects._ID, Projects._ID);
		projectsProjectionMap.put(Projects.NAME, Projects.NAME);
		projectsProjectionMap.put(Projects.TYPE, Projects.TYPE);
		projectsProjectionMap.put(Projects.LASTSYNC, Projects.LASTSYNC);
	}

	public static long getId(Uri uri) {
		return ContentUris.parseId(uri);
	}
}
